import { operationCode } from "../../../utils/config";
import { Web_Socket } from "../../../utils/socket";
import { checkLogin, Uint8Array2HexStr } from "../../../utils/util";

const code =  operationCode

// pages/index/add/add.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        formData: {},
        rules: [{
                name: 'sn',
                rules: {required: true, message: '请输入设备ID'},
            }, {
                name: 'password',
                rules: [{required: true, message: '请输入访问密码'}, {rangelength: [3,16], message: '密码长度3-16位'}],
            }]
    },

    formInputChange(e) {
        const {field} = e.currentTarget.dataset
        this.setData({
            [`formData.${field}`]: e.detail.value
        })
    },

    submitForm() {

        if (!checkLogin()) {
            return;
        }

        this.selectComponent('#form').validate((valid, errors) => {
            if (!valid) {
                const firstError = Object.keys(errors)
                if (firstError.length) {
                    wx.showToast({
                      title: errors[firstError[0]].message,
                      icon: 'error'
                    })
                }
            } else {
                const {sn} = this.data.formData;
               wx.$http.get({url: '/szm/device/sn/' + sn}).then(res => {
                    wx.setStorageSync('deviceKey', res.data)
                    this.post();
               }).catch();
            }
        })
    },

    post() {
        const {password} = this.data.formData;
        const ps = Array.from(password).map(p => p.charCodeAt(0));
        const message = {
            deviceKey: wx.getStorageSync('deviceKey'),
            kvMap: {
                [code.add]: ps
            }
        }
        const {deviceKey, kvMap} = message;
        Object.keys(kvMap).forEach(i => console.log(`add页面 ${deviceKey}=>请求`, `指令Hex[${parseInt(i).toString(16).toUpperCase().padStart(4, '0')}]`, `值Hex[${Uint8Array2HexStr(kvMap[i], ',')}]`))
        
        wx.$http.post({url: '/szm/netty/postOthers', data: message}).then(res => {
        });
    },

    socketOnMessage() {
        wx.$eventEmitter.off('add');
        wx.$eventEmitter.on('add', data => {
            const { kvMap } = data;
            Object.keys(kvMap).forEach(k => {
                const bCode = parseInt(k);
                const value = kvMap[bCode].length > 1 ? 1 : 0 ;
                if (bCode === code.add) {
                    wx.showToast({
                      title: `绑定设备` + (value ? '' : '失败'),
                      icon: value ? 'success' : 'error' 
                    })
                    if (value) {
                        setTimeout(() => {
                            wx.navigateBack()
                        }, 2000);
                    }
                }
            });
        })    
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.socketOnMessage();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        Web_Socket.buildSocket('add');
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})